package com.ynding.cloud.auth.server.admin.service.impl;

import com.ynding.cloud.auth.api.admin.domain.MenuDO;
import com.ynding.cloud.auth.api.admin.domain.UserDO;
import com.ynding.cloud.auth.api.admin.entity.Role;
import com.ynding.cloud.auth.server.admin.service.IMenuService;
import com.ynding.cloud.auth.server.admin.service.IResourceService;
import com.ynding.cloud.auth.server.admin.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>资源service </p>
 *
 * @author ynding
 * @version 2021/6/18
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class ResourceServiceImpl implements IResourceService {

    private final IMenuService menuService;
    private final IUserService userService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 获取请求url 对应的访问权限
     * @param requestUrl 请求url
     * @return
     */
    @Override
    public List<ConfigAttribute> getAttributes(String requestUrl) {
        List<MenuDO> allMenu = menuService.findAll();
        for (MenuDO menu : allMenu) {
            if (antPathMatcher.match(menu.getUrl(), requestUrl) && menu.getRoles().size() > 0) {
                List<Role> roles = menu.getRoles();
                List<String> names = roles.stream().map(p -> p.getName()).collect(Collectors.toList());
                return SecurityConfig.createList(names.toArray(new String[names.size()]));
            }
        }
        //没有匹配上的资源，都是登录访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Set<String> findResourcesByUsername(String username) {
        UserDO userDO = userService.loadUserByUsername(username);
        List<Role> roles = userDO.getRoles();
        return roles.stream().map(Role::getName).collect(Collectors.toSet());
    }

}
